package miner

import (
	"google.golang.org/grpc"
	"hundsun.com/hsl/hschain/common/log/logging"
	"hundsun.com/hsl/hschain/protos"
	"hundsun.com/hsl/hschain/protos/consensus/raft"
)

const (
	goroutineTagRaftConsensusClient = "raftcli"
	logFieldRaftSrv                 = "raftsrv"
)

// NewRatfConsensusClient 新建raft共识客户端
func NewRatfConsensusClient(module *RaftMiner, target *raft.Miner) (*RaftConsensusClient, error) {
	conn, err := grpc.Dial(target.PeerID, grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	e := &RaftConsensusClient{}
	e.conn = conn
	e.target = target
	e.module = module
	e.log = module.Log.WithField(logging.LogFieldGoroutine, goroutineTagRaftConsensusClient).WithField(logFieldRaftSrv, protos.Address(e.target.Address).GetShortString())
	e.pbClient = raft.NewRaftConsensusClient(e.conn)
	return e, nil
}

func (c *RaftConsensusClient) stop() error {
	if c.conn != nil {
		c.log.Trace("stopping")
		err := c.conn.Close()
		return err
	}
	return nil
}

// RaftConsensusClient raft consensus client
type RaftConsensusClient struct {
	module   *RaftMiner
	log      logging.Log
	conn     *grpc.ClientConn
	target   *raft.Miner
	pbClient raft.RaftConsensusClient
}
